var app = getApp();
var util = require('../../utils/util.js');
// socket连接
var socketOpen = false;
var frameBuffer_Data, session, SocketTask;
var socketColes=false;
// var url = util.api + '/jeeplus/layIMSocketServer?id=17313014726';

// var url = 

var upload_url = util.api+'/iim/contact/uploadImage';

var heart = '';

var sendHeart=true;
// 心跳失败次数
var heartBeatFailCount = 0
// 终止心跳
var heartBeatTimeOut = null;


Page({
  data: {
    user_input_text: '',//用户输入文字
    inputValue: '',
    returnValue: '',
    addImg: false,
    //格式示例数据，可为空
    allContentList: [],

    record:0,

    num: 0,

    userid:'',
    userphoto:'',
    username:'',
    layGroupId:'',
    avatar:'',
    layGrId:'',//发送者id


    url:'',
    upload_url:'',

    information:false,

    type:'',

    telephone: wx.getStorageSync('isRegistered'),
    userName:'', // name
    companyName:'',  // 公司名字
    position:'',   // 职位
    email:'',      // 邮箱
    chatname:'',// 

    navH:0,
  
    hideHeader: true,
    hideBottom: true,
  
    Loadingtime:'', // 定时器
    height:'0',
    false:false,
    // perfectInformat:true,// 
    // refreshTime: '', // 刷新的时间 
    height_01:0,

  },
 

  // 页面加载
  onLoad: function (options) {

    var date = new Date();

    this.setData({
      navH: app.globalData.navHeight,
      chatname:options.chatname,
      scrollHeight: (app.globalData.height_01-70)*2
    })
    
    

    var that = this;


    // that.setData({
    //   type:options.type,
    //   url:'wss://www.cdlpkj.cn/school/layIMSocketServer?id='+wx.getStorageSync('loginName')
    // })

    that.setData({
      type:options.type,
      url:util.wss
    })
    
// 创建连接
    socketColes == false;
    // wx.request({
    //   url: util.api+"/iim/im/viewUser",
    //   data: {id:wx.getStorageSync('userId')},
    //   success: function(res) {
    //     var tmpsig = res.data;
    //     if(tmpsig.success){

    //       console.log(tmpsig.body.data.hasOwnProperty('mobile'))

    //       if(!tmpsig.body.data.hasOwnProperty('mobile')){
    //         // wx.reLaunch({
    //         //   url: '../login/login'
    //         // })
    //       }else{
    //         wx.setStorageSync('isRegistered', tmpsig.body.data.mobile);

    //         that.index(options.type)
    //       }
    //     }
    //   },
    //   fail: function(resp) {
    //     console.log("getUserSigByTelephone failed,the response is %o", resp)
    //     return false;
    //   }
    // })


  },

  onUnload: function () {//如果页面被卸载时被执行
      console.log('如果页面被卸载时被执行')
      // wx.showModal({
      //   title: '提示',
      //   content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      // })
      let that=this
      // 清未读数据
      // clearInterval(that.data.Loadingtime)
      if(wx.getStorageSync('im')!=null&&wx.getStorageSync('im')!=''){
        var im=wx.getStorageSync('im');
        var chatlog=im.chatlog;
  
        var group=im.group;
  
          for(let key in im.group){
  
               if(key==that.data.layGroupId){
                
                console.log('')
  
                // group[that.data.layGroupId]= ({ message: 0 ,layGroup:tmpsig.body.layGroup , clickURL:'../mlcchat/mlcchat'} );\
  
                group[that.data.layGroupId]=({ message: 0 ,layGroup:group[that.data.layGroupId].layGroup,clickURL:group[that.data.layGroupId].clickURL});
  
                wx.setStorageSync("im",{chatlog,group});
                break;
               }
            }
        }

      socketColes=true;
      SocketTask.close();
      socketOpen=false;
  },

  onsocketload:function(e){
    var that = this;
    SocketTask.onOpen(res => {
      socketOpen = true;
      console.log('监听 WebSocket 连接打开事件。', res);
      that.sendTelephone();
    })
    SocketTask.onClose(onClose => {
      console.log('监听 WebSocket 连接关闭事件。', onClose)
      socketOpen = false;
      console.log(socketColes);
      if(!socketColes){
        this.webSocket();
      }
    })
    SocketTask.onError(onError => {
      console.log('监听 WebSocket 错误。错误信息', onError)
      socketOpen = false
    })


    SocketTask.onMessage(onMessage => {
      
      console.log('监听WebSocket接受到服务器的消息事件。服务器返回的消息', onMessage.data)

      if (wx.getStorageSync('userType') != "1") {

      wx.request({
        url: util.api+"/iim/im/viewUser",
        data: {id:wx.getStorageSync('userId')},
        success: function(res) {
          var tmpsig = res.data;
          if(tmpsig.success){
            console.log(tmpsig.body.data.hasOwnProperty('companyName'))

            if(!tmpsig.body.data.hasOwnProperty('companyName') && app.globalData.perfectInformat ){
              console.log('执行1243')
              app.perfectInformation()

              app.globalData.perfectInformat=false

              // that.app.globalData({
              //   perfectInformat:false
              // })

            }

          }
        },
        fail: function(resp) {
          console.log("getUserSigByTelephone failed,the response is %o", resp)
          return false;
        }
      });

      }


      var msg = onMessage.data;

      if (msg.indexOf("_msg_") >= 0) {
        var arra = msg.split("_msg_");
        var sender = arra[0];//群組id
        var receiver = arra[1];//发送者登录名
        var content = arra[2];//内容
        var avatar = arra[3];
        var type = arra[4];
        var senderName = arra[5];//发送者姓名
        var sendtime = arra[6];

          // layim.getMessage({
          //   username: senderName
          //   , avatar: avatar
          //   , id: sender
          //   , type: type
          //   , content: content
          // });

          console.log(sender)
          console.log(senderName)

          if(content.indexOf('img[')>=0){

            var arra1 = content.replace("img[","").replace("]","");

            console.log(arra1)

            that.data.allContentList.push({ is_ai: true, img: util.imgurl+arra1, avatar: avatar ,name:senderName,sender:sender});
      
          }else{
              that.data.allContentList.push({ is_ai: true, text: content, avatar:  avatar ,name:senderName,sender:sender});
          }

         
          that.setData({
            allContentList: that.data.allContentList
          })

          
             

          console.log(content)

          console.log(content.indexOf('img[')>=0)


          if(content.indexOf('img[')>=0){

            var arra1 = content.replace("img[","").replace("]","");

            console.log(arra1)

            var list1=({ is_ai: true, img: util.imgurl+arra1, avatar:  avatar ,name:senderName,sender:sender});


          }else{
            var list1=({ is_ai: true, text: content, avatar: avatar ,name:senderName,sender:sender});
          }

          console.log('储存')
          
          if(wx.getStorageSync('im')!=null&&wx.getStorageSync('im')!=''){
            var chatlog={};
            var is=false;
            var list=new Array();
            var im=wx.getStorageSync('im');
            var group=im.group;

             if(im.chatlog!=null&&im.chatlog!=''){
              chatlog=im.chatlog;
                for(let key in im.chatlog){
                  console.log(key+"---------"+sender);
                   if(key==sender){

                    console.log("进入2");
                    list=im.chatlog[key];
                    list.push(list1);
                    chatlog[sender]=list;
                    is=true;

                    let a= group[sender].message+1;

                    console.log(a)

                    group[sender]=({ message: a ,layGroup:group[sender].layGroup,clickURL:group[sender].clickURL});

                    // group[sender]=tmpsig.body.layGroup.unreadMessage+1;
                    // wx.setStorageSync("im",{chatlog,group});

                    break;
                   }
                }
                if(is==false){
                  list.push(list1);
                  chatlog[sender]=list;
                }
             }else{
              list.push(list1);
              chatlog[sender]=list;
             }
             wx.setStorageSync("im",{ group,chatlog});
          }
      
        }
        that.bottom()
    });

  },

  onShow: function (e) {

    if (!socketOpen) {
      this.webSocket()
    }

  },
  // 页面加载完成
  onReady: function () {

    console.log(SocketTask);

    //this.onsocketload();

    var that = this;

    setInterval(function () {
      console.log("----heartbeat----"+socketOpen+","+sendHeart);
      if (socketOpen && sendHeart){
        that.startHeartBeat();
      }else{  
      }
    }, 10*2000);


  },

  webSocket: function () {

    var me=this;
    console.log("the wss server addr is "+me.data.url)

    // 创建Socket
    console.log(me.SocketTask);

    SocketTask = wx.connectSocket({
      url:'wss://xuezhou.xyz/wss',
      // data: 'data',
      // header: {
      //   'content-type': 'application/json'
      // },
      // method: 'get',
      success: function (res) {
        console.log('WebSocket连接创建', res);

        me.unreadInformation()
  

        socketOpen = true;
        setTimeout(() => {
          me.onsocketload();
        }, 100);
      
      },
      fail: function (err) {
        console.log("failed to connect to wss server")
        wx.showToast({
          title: '网络异常！',
        })
        console.log(err)
      },
    })

    wx.onSocketOpen(function (res) {
      socketOpen = true
      
        sendSocketMessage("hello");
      
    })

  },

  // 提交文字
  submitTo: function (e) {

    let that = this;

    if(that.data.inputValue==null ||that.data.inputValue=='' ||that.data.inputValue==' '){
      return
    }
    console.log(that.data.inputValue);

    var data = {
      body: that.data.inputValue,
    }
    console.log("the input value is ", data)

    if (socketOpen) {
      
      var msg = data.body;
     
      sendSocketMessage(msg)

      this.data.allContentList.push({ is_my: { text: this.data.inputValue } });


      var list1=({ is_my: { text: that.data.inputValue ,user:that.data.userid ,username:that.data.username} });


      this.setData({
        allContentList: this.data.allContentList,
        inputValue: ''
      })

      console.log('储存')

      // that.data.allContentList.push({ is_ai: true, text: that.data.inputValue, avatar: util.url + avatar ,name:senderName,});

      if(wx.getStorageSync('im')!=null&&wx.getStorageSync('im')!=''){
        var chatlog={};
        var is=false;
        var list=new Array();
        var im=wx.getStorageSync('im');
        var group=im.group;
         if(im.chatlog!=null&&im.chatlog!=''){
          
          chatlog=im.chatlog;
          
            for(let key in im.chatlog){
              console.log(key+"---------"+that.data.layGroupId);

               if(key==that.data.layGroupId){
                console.log("进入2");
                list=im.chatlog[key];
                list.push(list1);
                chatlog[that.data.layGroupId]=list;
                is=true;
                break;
               }
            }
            if(is==false){
              list.push(list1);
              chatlog[that.data.layGroupId]=list;
            }
         }else{
          list.push(list1);
          chatlog[that.data.layGroupId]=list;
         }

         wx.setStorageSync("im",{ group,chatlog});

      }
      // else{
      //   var allContentList={};
      //   allContentList[that.data.layGroupId]=tmpsig.body.layGroup;
      //   wx.setStorageSync("im",{ allContentList});
      // }
      // wx.setStorageSync('allContentList', this.data.allContentList);
      

      console.log(that.data.allContentList)
      that.bottom()
    }
    else {
      console.log("the websocket is closed!")
      if (!socketOpen) {
        this.webSocket();
        if (socketOpen) {
          // 打开了socket就发送数据给服务器
          sendSocketMessage(data)
          this.data.allContentList.push({ is_my: { text: this.data.inputValue } });
          this.setData({
            allContentList: this.data.allContentList,
            inputValue: ''
          })
        }
      }

    }
  },
  bindKeyInput: function (e) {
    this.setData({
      inputValue: e.detail.value
    })
  },

  onHide: function () {
    SocketTask.close(function (close) {
      console.log('关闭 WebSocket 连接。', close)

      // SocketTask.close();

    });
    sendHeart=false;
  },

  upimg: function () {
    var that = this;
    wx.chooseImage({
      sizeType: ['original', 'compressed'],
      success: function (res) {
        
        that.setData({
          img: res.tempFilePaths[0]
        })
        // console.log(res.tempFilePaths)
        // console.log(upload_url)
        var imgurl=res.tempFilePaths[0]
        wx.uploadFile({
          url: upload_url,
          filePath: imgurl,
          name: 'file',
          success: function (res1) {
            console.log(res1)
            let newData = JSON.parse(res1.data);
            var data = {
              body:util.imgurl+newData.data.src
            }
           
            if (socketOpen) {
              var msg = that.data.userid+"_msg_"+that.data.layGroupId+"_msg_"+'img['+newData.data.src+']'+"_msg_"+that.data.userphoto+"_msg_group_msg_"+that.data.username+"_msg_NAN";
              sendSocketMessage(msg)
              that.data.allContentList.push({is_my:{ img:util.imgurl+newData.data.src} })
              that.setData({
                allContentList: that.data.allContentList,
              })
              var list1=({ is_my: { img: util.imgurl+newData.data.src  ,user:that.data.userid ,username:that.data.username} });
              
              if(wx.getStorageSync('im')!=null&&wx.getStorageSync('im')!=''){
                    var chatlog={};
                    var is=false;
                    var list=new Array();
                    var im=wx.getStorageSync('im');
                    var group=im.group;
                    if(im.chatlog!=null&&im.chatlog!=''){
                      
                      chatlog=im.chatlog;
                      
                        for(let key in im.chatlog){
                          console.log(key+"---------"+that.data.layGroupId);

                          if(key==that.data.layGroupId){
                            console.log("进入2");
                            list=im.chatlog[key];
                            list.push(list1);
                            chatlog[that.data.layGroupId]=list;
                            is=true;
                            break;
                          }
                        }

                        if(is==false){
                          list.push(list1);
                          chatlog[that.data.layGroupId]=list;
                        }
                    }else{
                      list.push(list1);
                      chatlog[that.data.layGroupId]=list;
                    }

                    wx.setStorageSync("im",{ group,chatlog});

                  }

              that.bottom()
            }else {
              console.log("the websocket is closed!")

              if (!socketOpen) {

                that.webSocket();

                if (socketOpen) {
                  // 打开了socket就发送数据给服务器

                  console.log("the input value is 断开", data)

                  sendSocketMessage(data)

                  that.data.allContentList.push({ is_my: { img:util.imgurl+newData.data.src } });

                  that.setData({
                    allContentList: that.data.allContentList,
                  })

                
                var list1=({ is_my: { img: util.imgurl+newData.data.src  ,user:that.data.userid ,username:that.data.username} });
                console.log('储存')
             
            
                  if(wx.getStorageSync('im')!=null&&wx.getStorageSync('im')!=''){
                      var chatlog={};

                      var is=false;
                      var list=new Array();
                      var im=wx.getStorageSync('im');
                      var group=im.group;
                      if(im.chatlog!=null&&im.chatlog!=''){
                        
                        chatlog=im.chatlog;
                        
                          for(let key in im.chatlog){
                            console.log(key+"---------"+that.data.layGroupId);

                            if(key==that.data.layGroupId){
                              console.log("进入2");
                              list=im.chatlog[key];
                              list.push(list1);
                              chatlog[that.data.layGroupId]=list;
                              is=true;
                              break;
                            }
                          }

                          if(is==false){
                            list.push(list1);
                            chatlog[that.data.layGroupId]=list;
                          }
                      }else{
                        list.push(list1);
                        chatlog[that.data.layGroupId]=list;
                      }

                      wx.setStorageSync("im",{ group,chatlog});

                    }
          
                // wx.setStorageSync('allContentList', that.data.allContentList);
                }
              }
            }
            // wx.showToast({
            //   title: '图片发送成功！',
            //   duration: 3000
            // });

          }
        })
        // that.data.allContentList.push({ is_my: { img: res.tempFilePaths } });

        // that.setData({
        //   allContentList: that.data.allContentList,
        // })
        // that.bottom();
      }
    })
  },


  addImg: function () {
    this.setData({
      addImg: !this.data.addImg
    })

  },
  // 获取hei的id节点然后屏幕焦点调转到这个节点  
  bottom: function () {
    var that = this;
    this.setData({
      scrollTop: 1000000
    })
  },
  // 开始心跳
  startHeartBeat: function () {
    console.log('socket开始心跳')
    var self = this;
    heart = 'heart';
    self.heartBeat();
  },

  // 结束心跳
  stopHeartBeat: function () {
    console.log('socket结束心跳')
    var self = this;
    heart = '';
    if (heartBeatTimeOut) {
      clearTimeout(heartBeatTimeOut);
      heartBeatTimeOut = null;
    }
    if (connectSocketTimeOut) {
      clearTimeout(connectSocketTimeOut);
      connectSocketTimeOut = null;
    }
  },

  // 心跳
  heartBeat: function () {
    var self = this;
    if (!heart) {
      return;
    }

    var msgJson = {
      msgtype:"heart",
      content: "this is heart",//发送的消息
    }
    sendSocketMessage(JSON.stringify(msgJson));
    }
  //end heartBeat
  ,sendTelephone:function(){
    var that=this;
    sendSocketMessage({
      msg: JSON.stringify({
        'telephone': app.globalData.identifier
      }),
      success: function (res) {
        console.log('send telephone successfully!');
      },

      

      fail: function (res) {
        console.log('send telephone failed');
          // 重连
          that.connectSocket();
      }
    });
  },//end sendTelephone


  index(type){

    console.log('zhixing')
  
    let that=this

    wx.request({
      url: util.api+"/iim/im/index",
      data: {
        token:wx.getStorageSync('token'),
        type:type
        },
        success: function(res) {
          var tmpsig = res.data;
  
          console.log("the return of getUserSigByTelephone is:"+ tmpsig);
  
          if(!tmpsig.success){
  
          }else{

            // console.log(tmpsig)
            
         //   var obj = JSON.parse(tmpsig.body.initjson);

            // console.log(obj)


            that.setData({
              userid:tmpsig.body.user.loginName,
              userphoto:tmpsig.body.user.photo,
              username:tmpsig.body.user.name,
              layGroupId:tmpsig.body.layGroup.id,
              avatar:tmpsig.body.layGroup.avatar,
            })

              app.phone(tmpsig.body.layGroup.id,type)

            // that.setData({
            //   Loadingtime:setInterval(function () {
            //     app.phone(tmpsig.body.layGroup.id,type)
            //   },1000)
            // })

           
            


            if(wx.getStorageSync('im')!=null&&wx.getStorageSync('im')!=''){
              var im=wx.getStorageSync('im');
              var chatlog=im.chatlog;
                for(let key in im.group){
                     if(key!=that.data.layGroupId){
                      var group=im.group;  
                      group[that.data.layGroupId]= ({ message: 0 ,layGroup:tmpsig.body.layGroup , clickURL:'../mlcchat/mlcchat'} );
                      wx.setStorageSync("im",{chatlog,group});
                     }
                  }

              }else{
                var group={};
                group[that.data.layGroupId]=({ message: 0 ,layGroup:tmpsig.body.layGroup, clickURL:'../mlcchat/mlcchat'} );
                wx.setStorageSync("im",{ group});
              }

            // 获取聊天记录
            if(wx.getStorageSync('im')!=null&&wx.getStorageSync('im')!=''){
              // var chatlog=im.chatlog;  
              var im=wx.getStorageSync('im');
              console.log(im.chatlog)

              for(let key in im.chatlog){
                if(key==that.data.layGroupId){
                    var list=[];
                    for(let i=im.chatlog[key].length-1;i>=0;i--){
                       list.push(im.chatlog[key][i]);
                      //  console.log(i)
                       if(i==im.chatlog[key].length-12){
                          break;
                       }
                    }

                    var list1=[];
                    for(let i=list.length-1;i>=0;i--){
                      list1.push(list[i])
                    }
                    console.log(list1);
                    that.setData({
                      allContentList:list1
                    })
                }
             }

             that.bottom()

          }
          // 清未读数据

          if(wx.getStorageSync('im')!=null&&wx.getStorageSync('im')!=''){
            var im=wx.getStorageSync('im');
            var chatlog=im.chatlog;
      
            var group=im.group;
      
              for(let key in im.group){
      
                   if(key==that.data.layGroupId){
                    
                    console.log('')
      
                    // group[that.data.layGroupId]= ({ message: 0 ,layGroup:tmpsig.body.layGroup , clickURL:'../mlcchat/mlcchat'} );\
      
                    group[that.data.layGroupId]=({ message: 0 ,layGroup:group[that.data.layGroupId].layGroup,clickURL:group[that.data.layGroupId].clickURL});
      
                    wx.setStorageSync("im",{chatlog,group});
                    break;
                   }
                }
            }
  
        
    
          }
        },
        fail: function(resp) {
          console.log("getUserSigByTelephone failed,the response is %o", resp)
          return false;
        },
      })
  },


  unreadInformation(){
    let that=this
    wx.request({
      url: util.api+"/iim/im/unreadInformation",
      data: {
        loginName:wx.getStorageSync('loginName'),
        },
        success: function(res) {
          var tmpsig = res.data;
          console.log("the return of getUserSigByTelephone is:" + tmpsig);

          console.log(tmpsig)

          if(!tmpsig.success){
  
          }else{
            
            for(let i=0;i<tmpsig.body.data.length;i++){
            var msg = tmpsig.body.data[i];

            if (msg.indexOf("_msg_") >= 0) {

              var arra = msg.split("_msg_");
              var sender = arra[0];//群組id
              var receiver = arra[1];//发送者登录名
              var content = arra[2];//内容
              var avatar = arra[3];
              var type = arra[4];
              var senderName = arra[5];//发送者姓名
              var sendtime = arra[6];
      
      
                console.log(sender)
                console.log(senderName)
      



              if(content.indexOf('img[')>=0){

                    var arra1 = content.replace("img[","").replace("]","");
                    that.data.allContentList.push({ is_ai: true, img: util.imgurl+arra1, avatar: util.url + avatar ,name:senderName,sender:sender});
                  }else{
                      that.data.allContentList.push({ is_ai: true, text: content, avatar: util.url + avatar ,name:senderName,sender:sender});
                  }

                  that.setData({
                    allContentList: that.data.allContentList
                  })


                  if(content.indexOf('img[')>=0){
                    var arra1 = content.replace("img[","").replace("]","");
                    console.log(arra1)
                    var list1=({ is_ai: true, img: util.imgurl+arra1, avatar: util.url + avatar ,name:senderName,sender:sender});
                  }else{
                    var list1=({ is_ai: true, text: content, avatar: util.url + avatar ,name:senderName,sender:sender});
                  }

      
                that.setData({
                  allContentList: that.data.allContentList
                })
      
                console.log('储存')
      
                
                if(wx.getStorageSync('im')!=null&&wx.getStorageSync('im')!=''){
                  var chatlog={};
                  var is=false;
                  var list=new Array();
                  var im=wx.getStorageSync('im');
                  var group=im.group;
      
                   if(im.chatlog!=null&&im.chatlog!=''){
                    chatlog=im.chatlog;
                      for(let key in im.chatlog){
                        console.log(key+"---------"+sender);
                         if(key==sender){
      
                          console.log("进入2");
                          list=im.chatlog[key];
                          list.push(list1);
                          chatlog[sender]=list;
                          is=true;
      
                          let a= group[sender].message+1;
      
                          console.log(a)
      
                          group[sender]=({ message: a ,layGroup:group[sender].layGroup,clickURL:group[sender].clickURL}); 
                  
                          break;
                         }
                      }
                      if(is==false){
                        list.push(list1);
                        chatlog[sender]=list;
                      }
                   }else{
                    list.push(list1);
                    chatlog[sender]=list;
                   }
                   wx.setStorageSync("im",{ group,chatlog});
                }
            
              }
            }
              that.bottom()


          }
        },
        fail: function(resp) {
          console.log("getUserSigByTelephone failed,the response is %o", resp)
          return false;
        },
      })
  },


  onGotUserInfo: function(e) {
    var that=this;
    // get the user head image
    /**
     * 获取用户信息
     */

     let userId=wx.getStorageSync('userId')

     console.log(userId)

     if(userId){
      wx.request({
        url: util.api+"/iim/im/viewUser",
        data: {
          id:wx.getStorageSync('userId')
        },
        success: function(res) {
          var tmpsig = res.data;

          // console.log(tmpsig)
  
          if(tmpsig.success){
            // console.log(tmpsig.body.data.name)
            that.setData({
              userName:tmpsig.body.data.name,
              companyName:tmpsig.body.data.companyName,
              position:tmpsig.body.data.position,
              email:tmpsig.body.data.email,
            })
          }
  
          if(!tmpsig.success){
            wx.showToast({
              title: tmpsig.msg,
              duration: 2000
            });
          }
        },
        fail: function(resp) {
          console.log("getUserSigByTelephone failed,the response is %o", resp)
          return false;
        }
      })}
    },

    informations(){
      this.setData({
        information:true
      })
    },

    informationbg(){

      
      this.setData({
        information:false
      })

    },


    //f返回

    navBack(){
      let that=this;

      if (wx.getStorageSync('userType')=="1") {
        wx.navigateBack({
          delta: 1,
        })
      }else{
        wx.showModal({
          title: '提示',
          content: '您是否退出当前服务',
          confirmText: "确定",
          cancelText: "取消",
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击了确认退出操作')
              wx.request({
                url: util.api + "/iim/im/kickOut",
                data: {
                  token: wx.getStorageSync('token'),
                  id: that.data.layGroupId,
                  type: that.data.type
                },
                success: function (res) {
                  var tmpsig = res.data;
                  console.log("the return of getUserSigByTelephone is:" + tmpsig);
                  if (!tmpsig.success) {

                  } else {
                    wx.navigateBack({
                      delta: 1,
                    })
                  }
                },
                fail: function (resp) {
                  console.log("getUserSigByTelephone failed,the response is %o", resp)
                  return false;
                },
              })

            } else {
              wx.navigateBack({
                delta: 1,
              })
              console.log('用户点击取消操作')
            }
          }

        });


      }

     
    },

    
 // 下拉刷新
 refresh: function (e) {
  // 显示顶部刷新图标
  console.log('下拉')
  let that=this

  // var date = new Date();

  that.setData({
    // refreshTime: date.toLocaleTimeString(),
    hideHeader: false
  })

  if(wx.getStorageSync('im')!=null&&wx.getStorageSync('im')!=''){

    // var chatlog=im.chatlog;  
    var im=wx.getStorageSync('im');

    // console.log(im.chatlog)

    for(let key in im.chatlog){
      if(key==that.data.layGroupId){
          var list=[];
          for(let i=im.chatlog[key].length-1;i>=0;i--){
             list.push(im.chatlog[key][i]);
            //  console.log(i)
             if(i==im.chatlog[key].length-12- that.data.allContentList.length){
                break;
             }
          }

          // console.log(list)

          var list1=[];
          
          for(let i=list.length-1;i>=0;i--){
            list1.push(list[i])
          }
          this.data.allContentList=list1;

          // console.log(list1);

          // this.data.allContentList.push()

  
          that.setData({
            allContentList:this.data.allContentList,
            hideHeader: true
          })
           // 隐藏导航栏加载框
         
      }
   }
}

},


formSubmit: function(e) {

  console.log( 'formid'+e.detail.formId)

  if (e.detail.formId != 'the formId is a mock one' && e.detail.formId!='') {
    wx.request({
      url: util.api+"/iim/im/saveFromid",
      data: {
        token:wx.getStorageSync('token'),
        fromid:e.detail.formId
        },
        success: function(res) {
          var tmpsig = res.data;
          console.log("the return of getUserSigByTelephone is:" + tmpsig);
          console.log(res)
          if(!tmpsig.success){
          
          }else{
           
          }
        },
        fail: function(resp) {
          console.log("getUserSigByTelephone failed,the response is %o", resp)
          return false;
        },
      })
  }
},




bindfocus: function(e) {

  let that = this;
  let height = 0;
  let height_02 = 0;
  wx.getSystemInfo({
  success: function (res) {
   height_02 = res.windowHeight;
  }
  })
  console.log(e.detail.height+'-------'+app.globalData.height_01+'-----------'+height_02)

  height = e.detail.height - (app.globalData.height_01 - height_02);
  console.log('app is', app.globalData.height_01);
    that.setData({
        height: (height*2)-90,
        scrollHeight:(app.globalData.height_01-height-10)*2,
    })
  
    that.bottom();
 

  console.log('获得焦点的 e is', e);
  },
      
      //监听input失去焦点
      
    bindblur: function(e) {
      
    

      this.setData({
        height:0,
        scrollHeight: (app.globalData.height_01-70)*2
      });

      this.bottom();
    

      console.log('失去焦点的 e is', this.data.height);
  },



})





//通过 WebSocket 连接发送数据，需要先 wx.connectSocket，并在 wx.onSocketOpen 回调之后才能发送。
function sendSocketMessage(msg) {
  if (socketOpen) {
    wx.sendSocketMessage({
      data: msg,
      success:function(successRet){
        console.log("send success,the return is ")
        console.log(successRet)
      },
      fail:function(failRet){
        console.log("send failed,the return is "+failRet.errMsg)
      }
    })
  } else {
    console.log("the websocket is not open")
  }
};


